#include "channelnamewidget.h"
#include "dm/dmdef.h"
#include "globalconfig.h"

ChannelNameLineEdit::ChannelNameLineEdit(const uint8_t &index, QWidget *parent)
    : ALineEdit{parent}
    , m_index{index}
{
    setValidator(new QRegExpValidator(QRegExp("[A-Za-z !-~]*"), this));
    setMaxLength(NAME_LEN_CH - 1);
    connect(this, &ALineEdit::textConfirmed, this, [=](QString text) {
        emit stateChanged(m_index, text.leftJustified(NAME_LEN_CH, '\0', true));
    });

}

ChannelNameWidget::ChannelNameWidget(QWidget *parent)
    : AGroupBox{tr(LABEL_CHANNEL_NAME), parent}
{
    auto layout = new QVBoxLayout(this);
    auto gLayout = new QGridLayout;
    layout->addLayout(gLayout);
    layout->addStretch();

    const auto space = 18 * ratio();
    gLayout->setSpacing(space);
    gLayout->setContentsMargins(space, space, space, space);

    gLayout->addWidget(new ALabel(tr(LABEL_INPUT_NAME), this), 0, 0, Qt::AlignHCenter);
    gLayout->addWidget(new ALabel(tr(LABEL_OUTPUT_NAME), this), 0, 1, Qt::AlignHCenter);

    const auto cfgName = GlobalConfig::getInstance().cfgName();
    const auto cfgDev = GlobalConfig::getInstance().cfgDev();
    for (int i = 0; i < cfgDev.mus.tru_ch; ++i) {
        auto edit = new ChannelNameLineEdit(i, this);
        edit->setText(cfgName.mus[i]);
        gLayout->addWidget(edit, i + 1, 0, Qt::AlignHCenter);
        connect(edit, &ChannelNameLineEdit::stateChanged, &GlobalConfig::getInstance(), &GlobalConfig::writeInputName);
    }
    for (int i = 0; i < cfgDev.out.tru_ch; ++i) {
        auto edit = new ChannelNameLineEdit(i, this);
        edit->setText(cfgName.out[i]);
        gLayout->addWidget(edit, i + 1, 1, Qt::AlignHCenter);
        connect(edit, &ChannelNameLineEdit::stateChanged, &GlobalConfig::getInstance(), &GlobalConfig::writeOutputName);
    }
}


